package cn.edu.abtu.service.impl;

import cn.edu.abtu.service.MsmService;
import cn.edu.abtu.utils.RandomUtil;
import cn.edu.abtu.vo.ResponseData;
import com.alibaba.druid.util.StringUtils;
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.TimeUnit;

@Service
public class MsmServiceImpl implements MsmService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public ResponseData sendCode(String phone) {
        String code = stringRedisTemplate.boundValueOps(phone).get();
        if (!StringUtils.isEmpty(code)){
            return ResponseData.success("验证码已发送,请勿频繁发送验证码",null);
        }
        Integer sdkAppID = 1400745211;
        String appKey = "5026058cb045267997e8089b15b9a3ad";
        Integer templateId = 1561861;
        String smsSign = "哇呜哈哈哈哈11公众号";
        code = RandomUtil.getFourBitRandom();
        try {
            String[] params = {code,"5"};
            SmsSingleSender smsSingleSender = new SmsSingleSender(sdkAppID,appKey);
            SmsSingleSenderResult result = smsSingleSender.sendWithParam("86",phone,templateId,params,smsSign,"","");
            //验证码发送成功后得到的result对象{"result":0,"errmsg":"OK","ext":"","sid":"3364:115938989516645912031252340","fee":1,"isocode":"CN"}
            if (result.errMsg.equals("OK")){
                stringRedisTemplate.boundValueOps(phone).set(code);
                stringRedisTemplate.boundValueOps(phone).expire(5, TimeUnit.MINUTES);
                return ResponseData.success("验证码发送成功"+code,result);
            }
            return ResponseData.fail("请核对电话号码是否正确!",null);
        }catch (Exception e){
            e.printStackTrace();
            return ResponseData.fail("验证码发送失败"+code,null);
        }
    }
}
